<template>
  <div class="product-query">
    <!-- 产品参数支持表 -->
    <el-row class="query-form" :gutter="20">
      <span>询价编号:</span>
      <el-col :span="3">
        <el-input
          v-model="filters.inquiryNumber"
          placeholder="请输入"
          clearable
        />
      </el-col>
      <span>产品图号:</span>
      <el-col :span="3">
        <el-input
          v-model="filters.pictureNumber"
          placeholder="请输入"
          clearable
        />
      </el-col>
      <span>状态:</span>
      <el-col :span="3">
        <el-select v-model="filters.status" placeholder="请选择" clearable>
          <el-option
            v-for="option in statusOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button color="#2F4050" @click="handleQuery">查询</el-button>
        <el-button color="#2F4050" @click="resetFilters">重置</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table :data="tableDataArray" stripe>
      <el-table-column
        width="200px"
        align="center"
        label="发起时间"
        prop="startTime"
      />
      <el-table-column
        width="100px"
        align="center"
        label="询价编号"
        prop="inquiryNumber"
      />
      <el-table-column
        width="120px"
        align="center"
        label="产品图号"
        prop="pictureNumber"
      />
      <el-table-column
        width="200px"
        align="center"
        label="索要类型"
        prop="productCategory"
      />
      <el-table-column
        width="100px"
        align="center"
        label="状态"
        prop="status"
        :formatter="formatStatus"
      />
      <el-table-column
        width="200px"
        align="center"
        label="原因"
        prop="reason"
      />
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <template v-if="row.status === 1">
            <el-button type="text" @click="handleNavigate(row)">回复</el-button>
            <el-button type="text">查看产品</el-button>
          </template>
          <template v-if="row.status === 2 || row.status === 3">
            <el-button type="text" @click="handleNavigate(row)">查看</el-button>
            <el-button type="text">查看产品</el-button>
          </template>
          <el-button
            v-if="row.status === 4"
            type="text"
            @click="handleNavigate(row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <PageBean
      :total="total"
      :page="page"
      :pageSize="pageSize"
      @update:page="handlePageChange"
      @update:pageSize="handlePageSizeChange"
      class="pagination"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import PageBean from "./utils/PageBean.vue";
import { getParameterList, getParamInfo } from "@/api/supplier/supplier";
import { useRouter } from "vue-router";
// 路径跳转
const router = useRouter();

// 查询参数
const filters = ref({
  inquiryNumber: "",
  pictureNumber: "",
  status: null
});

// 表格数据
const tableData = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);

// **确保 tableData 绑定的是数组**
const tableDataArray = computed(() => {
  return Array.isArray(tableData.value) ? tableData.value : [];
});

// 状态选项
const statusOptions = [
  { value: null, label: "全部" },
  { value: 1, label: "待回复" },
  { value: 2, label: "待审核" },
  { value: 3, label: "已通过" },
  { value: 4, label: "未通过" }
];

// **初始化加载全部数据**
const initData = async () => {
  try {
    const { data } = await getParameterList({ page: 1, pageSize: 10 });

    console.log("全部数据>>>", data);

    if (Array.isArray(data)) {
      tableData.value = data;
      total.value = data.length;
    } else {
      console.error("错误：返回的数据不是数组！", data);
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    tableData.value = [];
    total.value = 0;
  }
};

// **点击查询**
const handleQuery = async () => {
  try {
    // 处理 filters，防止 null 影响查询
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      inquiryNumber: filters.value.inquiryNumber || undefined,
      pictureNumber: filters.value.pictureNumber || undefined,
      status: filters.value.status ?? undefined // 确保 status 传 undefined 而不是 null
    };

    console.log("最终查询参数>>>", params); // 打印最终传给后端的参数

    const response = await getParamInfo(params);

    console.log("查询返回数据>>>", response);

    // 确保响应数据格式正确
    if (response?.data && Array.isArray(response.data)) {
      tableData.value = response.data;
      total.value = response.data.length;
    } else {
      console.error("错误：返回的数据格式不正确！", response);
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("查询失败:", error);
    tableData.value = [];
    total.value = 0;
  }
};

// **格式化状态显示**
const formatStatus = row => {
  const status = statusOptions.find(option => option.value === row.status);
  return status ? status.label : "-";
};

// **重置查询条件**
const resetFilters = () => {
  filters.value = {
    inquiryNumber: "",
    pictureNumber: "",
    status: null
  };
  initData(); // 重新加载所有数据
};

// **处理分页页码变化**
const handlePageChange = newPage => {
  page.value = newPage;
  handleQuery();
};

// **处理每页显示条数变化**
const handlePageSizeChange = newPageSize => {
  pageSize.value = newPageSize;
  page.value = 1;
  handleQuery();
};

// 点击跳转到产品参数页面
const handleNavigate = row => {
  localStorage.setItem("rowData", JSON.stringify(row)); // 存入 localStorage
  router.push({
    name: "parameter",
    query: { inquiryNumber: row.inquiryNumber } // 仍然用 query 传递 ID
  });
};

// **初始化数据**
onMounted(initData);
</script>

<style scoped>
.product-query {
  padding: 20px;
}

.query-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  background-color: #efefef;
  padding: 10px;
}
</style>
